/**
 * Copyright [2019] [LiBo/Alex of copyright liboware@gmail.com ]
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.hyts.dess.chat.service;

import com.alibaba.fastjson.JSONObject;
import com.hyts.dess.chat.constant.MessageTypeEnum;
import com.hyts.dess.chat.constant.SessionDataContainer;
import com.hyts.dess.chat.model.ChatMessage;
import com.hyts.dess.chat.utils.NettyAttrUtil;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

/**
 * @project-name:dess
 * @package-name:com.hyts.dess.chat.service
 * @author:LiBo/Alex
 * @create-date:2020-07-28 10:21
 * @copyright:libo-alex4java
 * @email:liboware@gmail.com
 * @description:
 */
@Slf4j
public class WebSocketService {

    /**
     * 清除会话信息
     * @param channel
     */
    public void clearSession(Channel channel) {
        // 获取以及生产相关的userId
        String userId = NettyAttrUtil.getUserId(channel);
        // 清除相关的会话信息
        SessionDataContainer.channelGroup.remove(channel);
        // 清除相关的用户信息
        SessionDataContainer.channelMap.remove(userId);
    }

    /**
     * 传输ping命令对象操作
     */
    public void sendPing(){
        ChatMessage chatMessage = new ChatMessage();
        chatMessage.setType(MessageTypeEnum.ping信息.getSubject());
        String message = JSONObject.toJSONString(chatMessage);
        TextWebSocketFrame tws = new TextWebSocketFrame(message);
        SessionDataContainer.channelGroup.writeAndFlush(tws);
    }

    /**
     * 从缓存中移除Channel，并且关闭Channel
     */
    public void scanNotActiveChannel() {
        Map<String, Channel> channelMap = SessionDataContainer.channelMap;
        // 如果这个直播下已经没有连接中的用户会话了，删除频道
        if (channelMap.size() == 0) {
            return;
        }
        for (Channel channel : channelMap.values()) {
            long lastHeartBeatTime = NettyAttrUtil.getLastHeartBeatTime(channel);
            long intervalMillis = (System.currentTimeMillis() - lastHeartBeatTime);
            if (!channel.isOpen()
                    || !channel.isActive()
                    || intervalMillis > 90000L) {
                channelMap.remove(channel);
                SessionDataContainer.channelGroup.remove(channel);
                if (channel.isOpen() || channel.isActive()) {
                    channel.close();
                }
            }
        }
    }


}
